package com.cust.zy.newtask.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.cust.zy.newtask.TaskApplication;

/**
 * Created by zhuangyuan on 4/15/2017.
 * 邮箱：zhuangyuan.k@qq.com
 */

public class SqlHelper {
    public static String TASK_TABLE = "Task";
    public static String WORD_TABLE = "Word";
    public static String WORD_NOTE_TABLE = "WordNote";
    public static String SCHEDULE_TABLE = "Schedule";
    public static String LOG = "NewTask";
    private DBOpenHelper dbOpenHelper;

    public SqlHelper(Context context) {
        this.dbOpenHelper = DBOpenHelper.getInstance(context);
    }

    public void Insert(Context context, String table, ContentValues values) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        try {
            db.insert(table, null, values);
        } catch (Exception e) {
            e.getStackTrace();
        }
        db.close();
    }

    public void Update(Context context, String table, ContentValues values, String whereClause, String[] whereArgs) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        try {
            db.update(table, values, whereClause, whereArgs);
        } catch (Exception e) {
            e.getStackTrace();
        }
        db.close();
    }

    public Cursor Query(Context context, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        Cursor cursor = null;
        try {
            cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
            Log.i(LOG, "query");
            Log.i("countofcursor=", "" + cursor.getCount());
        } catch (Exception e) {
            e.getStackTrace();
        }
        db.close();
        return cursor;

    }

    public void Delete(Context context, String table, String whereClause, String[] whereArgs) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        try {
            db.delete(table, whereClause, whereArgs);
            Log.i(LOG, "delete");
        } catch (Exception e) {
            e.getStackTrace();
        }
        db.close();
    }

    public void DeleteTable(Context context, String table) {

        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        String sql = "drop table " + table;
        try {
            db.execSQL(sql);
            Log.i(LOG, sql);
        } catch (Exception e) {
            e.getStackTrace();
        }
        db.close();
    }
}
